<?php
/**
 * Author: yixuan
 * Desc: 微信小程序封装类
 * Time: 2016/5/18 14:08
 */

namespace app\lib;

use think\Cache;
use think\Db;

class MiniProgramAccount
{
    private static $appid;
    private static $secret;
    private static $token;
    private static $encodingAesKey;

    static $instance = null;

    private function __construct()
    {
        global $_G, $_P;
        if (!isset($_P['i'])) {
            return ['errcode' => 1, 'msg' => '平台参数缺失'];
        }
        //获取平台信息($_P['i']即对应数据库中的主键ID， platform_type表示查询小程序类型的配置参数)
        $mp_info = Db::table('yx_sys_platform')->where(['id' => $_P['i'], 'platform_type' => 1])->find();
        // [debug]执行SQL: SELECT * FROM `yx_sys_platform` WHERE  `id` = 6  AND `platform_type` = 1 LIMIT 1

        if (empty($mp_info) || is_null($mp_info)) {
            return ['errcode' => 1, 'msg' => '小程序信息获取失败'];
        }
        if (empty($mp_info['appid']) || empty($mp_info['secret'])) {
            return ['errcode' => 1, 'msg' => '小程序信息参数为空'];
        }
        //挂载$_G['platform']
        $_G['platform'] = $mp_info;
        self::$appid = $mp_info['appid'];
        self::$secret = $mp_info['secret'];
        self::$token = $mp_info['token'];
        self::$encodingAesKey = $mp_info['encodingaeskey'];
    }

    public static function getInstance()
    {
        if (!self::$instance || is_null(self::$instance)) {
            self::$instance = new self();
        }
        return self::$instance;
    }


    /**
     * desc: 根据微信js_code获取当前用户的openid
     * @return mixed
     * @author: liud
     * @time: 2016/8/1 09:27
     */
    public function getUserOpenidByCode()
    {
        global $_P;
        $appid = self::$appid;
//        $secret = '392de4839f6036d576a0a3a40ec2e00c';
        $secret = self::$secret;
        $js_code = $_P['code'];
        $getUrl = "https://api.weixin.qq.com/sns/jscode2session?appid={$appid}&secret={$secret}&js_code={$js_code}&grant_type=authorization_code";

        return $this->requestApi($getUrl);
    }

    public function requestApi($url, $data = [], $isPost = false)
    {
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
        curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);

        if ($isPost) {
            curl_setopt($ch, CURLOPT_POST, 1);
            curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($data));
            // 如果API要求JSON格式，则添加此头信息
            curl_setopt($ch, CURLOPT_HTTPHEADER, ['Content-Type: application/json']);
        }

        $output = curl_exec($ch);
        $httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
        curl_close($ch);

        if ($httpCode == 200) {
            return json_decode($output, true);
        } else {
            throw new Exception("请求微信API失败，HTTP状态码：{$httpCode}");
        }
    }

}